package com.example.quartzdemo.controller;

import com.example.quartzdemo.dto.JobInfo;
import com.example.quartzdemo.repository.JobRepository;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import org.quartz.*;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author jasondai
 * @date 2023/10/25 10:08
 */
@RestController
@RequestMapping(value = "job")
@Validated
public class JobDetailController {
    @Resource
    private Scheduler scheduler;
    @Resource
    private JobRepository jobRepository;

    @PostMapping
    public Object createJob(@NotNull(message = "name 不能为空") @NotBlank(message = "name 不能为空") String name
            ,String group
            ,@NotNull(message = "jobClassName 不能为空") @NotBlank(message = "jobClassName 不能为空")String jobClassName
            ,@NotNull(message = "cron 不能为空") @NotBlank(message = "cron 不能为空")String cron) throws Exception {
        JobDetail jobDetail = JobBuilder.newJob(getClass(jobClassName).getClass())
                .withIdentity(name,group)
                .storeDurably()
                .build();
        // 0/10 * * * * ? *
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
        Trigger trigger = TriggerBuilder.newTrigger()
                .forJob(jobDetail)
                .withIdentity(name,group)
                .withSchedule(scheduleBuilder)
                .startNow()
                .build();
        Set<Trigger> set = new HashSet<>();
        set.add(trigger);
        scheduler.scheduleJob(jobDetail,set,true);
        return "OK";
    }

    @PostMapping("rescheduleJob")
    public Object rescheduleJob(@NotNull(message = "name 不能为空") @NotBlank(message = "name 不能为空") String name
            ,String group
            ,@NotNull(message = "newCron 不能为空") @NotBlank(message = "newCron 不能为空") String newCron) throws SchedulerException {
        TriggerKey triggerKey =TriggerKey.triggerKey(name,group);
        CronTrigger trigger = (CronTrigger)scheduler.getTrigger(triggerKey);
        Trigger newTrigger = trigger.getTriggerBuilder()
                .withIdentity(name,group)
                .withSchedule(CronScheduleBuilder.cronSchedule(newCron))
                .build();
        scheduler.rescheduleJob(triggerKey,newTrigger);
        return "OK";
    }

    @PostMapping("deleteJob")
    public Object delete(@NotNull(message = "name 不能为空") @NotBlank(message = "name 不能为空") String name,String group) throws SchedulerException {
        TriggerKey triggerKey =TriggerKey.triggerKey(name,group);
        JobKey jobKey = JobKey.jobKey(name,group);
        scheduler.pauseTrigger(triggerKey);
        scheduler.unscheduleJob(triggerKey);
        scheduler.deleteJob(jobKey);
        return "OK";
    }

    @PostMapping(value = "pauseJob")
    public Object pauseJob(@NotNull(message = "name 不能为空") @NotBlank(message = "name 不能为空") String name,String group) throws SchedulerException {
        scheduler.pauseJob(JobKey.jobKey(name,group));
        return "OK";
    }

    @PostMapping(value = "resumeJob")
    public Object resumeJob(@NotNull(message = "name 不能为空") @NotBlank(message = "name 不能为空") String name,String group) throws SchedulerException {
        scheduler.resumeJob(JobKey.jobKey(name,group));

        return "OK";
    }

    @GetMapping("/queryJobs")
    public List<JobInfo> queryJobs(){
        return jobRepository.queryJobs();
    }

    /**
     * 获取Job实例
     * @param classname
     * @return
     * @throws Exception
     */
    public static QuartzJobBean getClass(String classname) throws Exception {
        try {
            Class<?> c = Class.forName(classname);
            return (QuartzJobBean) c.getDeclaredConstructor().newInstance();
        } catch (Exception e) {
            throw new Exception("类["+classname+"]不存在！");
        }

    }
}
